package com.database;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

import com.database.EducationPad.EducationColumns;
import com.studay.bean.Const;
import com.util.LogManager;

public class EducationPovider extends ContentProvider {

	private static final String DATABASE_NAME = "education.db";
	private static final int DATABASE_VERSION = 2;
	private static final String CHANNEL_TABLE = "channel";
	private static final String PROJECT_TABLE = "project";
	private static final String COURSE_TABLE = "course";

	private DatabaseHelper mOpenHelper;
	private static final UriMatcher matcher;

	static {
		matcher = new UriMatcher(UriMatcher.NO_MATCH);
		matcher.addURI(Const.AUTHORITY, CHANNEL_TABLE, 1);
		matcher.addURI(Const.AUTHORITY, PROJECT_TABLE, 2);
		matcher.addURI(Const.AUTHORITY, COURSE_TABLE, 3);
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		switch (matcher.match(uri)) {
		case 1:// insert channel
			long rowId = db.insert(CHANNEL_TABLE, null, values);
			if (rowId > 0) {
				Uri eduUri = ContentUris.withAppendedId(
						EducationColumns.CHANNEL_URI, rowId);
				getContext().getContentResolver().notifyChange(eduUri, null);
				return eduUri;
			}
			throw new SQLException("Failed to insert row into" + uri);
		case 2:// insert project
			long pRowId = db.insert(PROJECT_TABLE, null, values);
			if (pRowId > 0) {
				Uri eduUri = ContentUris.withAppendedId(
						EducationColumns.PROJECT_URI, pRowId);
				getContext().getContentResolver().notifyChange(eduUri, null);
				return eduUri;
			}
			throw new SQLException("Failed to insert row into" + uri);
		case 3:// insert course
			long cRowId = db.insert(COURSE_TABLE, null, values);
			if (cRowId > 0) {
				Uri eduUri = ContentUris.withAppendedId(
						EducationColumns.COURSE_URI, cRowId);
				getContext().getContentResolver().notifyChange(eduUri, null);
				return eduUri;
			}
			throw new SQLException("Failed to insert row into" + uri);
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {

		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

		switch (matcher.match(uri)) {
		case 1:
			qb.setTables(CHANNEL_TABLE);
			break;
		case 2:
			qb.setTables(PROJECT_TABLE);
			break;
		case 3:
			qb.setTables(COURSE_TABLE);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor c = qb.query(db, projection, selection, selectionArgs, null,
				null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (matcher.match(uri)) {
		case 1:
			count = db.update(CHANNEL_TABLE, values, selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (matcher.match(uri)) {
		case 2:
			count = db.delete(PROJECT_TABLE, selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (matcher.match(uri)) {
		case 1:
			return EducationColumns.CONTENT_TYPE;
		case 3:
			return EducationColumns.CONTENT_TYPE;
		case 2:
			return EducationColumns.CONTENT_TYPE;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			LogManager.LogShow(Const.TAG, "创建数据库", LogManager.INFO);
			// create channel table
			db.execSQL("CREATE TABLE " + CHANNEL_TABLE
					+ " ([id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,"
					+ " [xmlUrl] VARCHAR(200) NOT NULL ,"
					+ " [version] VARCHAR(8) NOT NULL ,"
					+ " [protocl] VARCHAR(15) NULL ,"
					+ " [fisserverurl] VARCHAR(30) NULL ,"
					+ " [nodes] VARCHAR(8) NULL ,"
					+ " [groupNum] VARCHAR(8) NULL);");
			// create project table
			db.execSQL("CREATE TABLE " + PROJECT_TABLE
					+ " ([pid] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,"
					+ "[name] VARCHAR(20) NOT NULL,"
					+ "[channelId] INTEGER  NOT NULL,"
					+ "[remark] VARCHAR(200) NULL,"
					+ "[credit]  INTEGER NULL);");
			// create course table
			db.execSQL("CREATE TABLE " + COURSE_TABLE
					+ " ([cid] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,"
					+ "[name] VARCHAR(20)  NULL,"
					+ "[filehash] VARCHAR(20) NULL,"
					+ "[teacher] VARCHAR(20) NULL,"
					+ "[playlength] INTEGER NULL ,"
					+ "[teacherInfo] VARCHAR(100) NULL,"
					+ "[project] VARCHAR(100) NULL ,"
					+ "pid integer NOT NULL CONSTRAINT pid REFERENCES "
					+ PROJECT_TABLE + "(pid) ON DELETE CASCADE);");
			// create trigger
			db.execSQL("CREATE TRIGGER [ON_TBL_TABLEC_] BEFORE DELETE ON "
					+ PROJECT_TABLE + " FOR EACH ROW BEGIN DELETE from "
					+ COURSE_TABLE + " WHERE course.pid = OLD.pid;END;");

		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			LogManager.LogShow(Const.TAG, "Upgrading database from version " + oldVersion
					+ " to " + newVersion + ", which will destroy all old data", LogManager.INFO);
			db.execSQL("DROP TABLE IF EXISTS channel");
			db.execSQL("DROP TABLE IF EXISTS project");
			db.execSQL("DROP TABLE IF EXISTS course");
			onCreate(db);
		}
	}

	public static String getDATABASE_NAME() {
		return DATABASE_NAME;
	}

	public static int getDATABASE_VERSION() {
		return DATABASE_VERSION;
	}

	public static String getCHANNEL_TABLE() {
		return CHANNEL_TABLE;
	}

	public static String getPROJECT_TABLE() {
		return PROJECT_TABLE;
	}

	public static String getCOURSE_TABLE() {
		return COURSE_TABLE;
	}

}